package com.xuecheng.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
@Component
public class AuthInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取request中的payload
        String payload = request.getHeader("payload");
        if (StringUtils.isEmpty(payload)) {
            return true;
        }
        //2.解码生成json
        String json = URLDecoder.decode(payload, "utf-8");
        //3.将json转换成对象
        AuthInfo info = JSON.parseObject(json, AuthInfo.class);
        //4.将对象存到ThreadLocal
        AuthInfoHolder.setAuthInfo(info);
        //5.放行
        return true;
    }
}
